//
//  SHAlertManager.m
//  FeiFan
//
//
//  Copyright © 2019年 . All rights reserved.
//

#import "SHAlertManager.h"


@interface SHAlertManager ()
@property (strong, nonatomic) NSMutableArray *hudStack;
@end

@implementation SHAlertManager

+ (instancetype)sharedInstance {
    static __strong SHAlertManager *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self.class new];
    });
    return _instance;
}
- (instancetype)init {
    if (self = [super init]) {
        _hudStack = [NSMutableArray array];
    }
    return self;
}

#pragma mark - UIWindow
- (UIWindow *)overlayWindow
{
    static UIWindow *overlay = nil;
    if (overlay == nil) {
        overlay = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
        overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        overlay.backgroundColor = UIColor.clearColor;
        overlay.windowLevel = UIWindowLevelStatusBar;
    }
    return overlay;
}
- (void)showHUD:(UIViewController<SHAlertManagerDelegate> *)hud
{
    
    
    if (self.overlayWindow.hidden) {
        // 当前没显示任何内容时，直接显示
        [_hudStack addObject:hud];
        [self showNext];
    } else {
        if (self.overlayWindow.rootViewController == hud) {
            // 当前显示的即为此模板，直接更新
            if ([hud respondsToSelector:@selector(updateImmediately)]) {
                [hud updateImmediately];
            }
        } else {
            // 准备之后显示
            if (![_hudStack containsObject:hud]) {
                [_hudStack addObject:hud];
            }
        }
    }
}
- (void)showNext
{
    if (_hudStack.count) {
        // 显示下一级页面
        UIViewController<SHAlertManagerDelegate> *hud = _hudStack.firstObject;
        [self.overlayWindow setRootViewController:hud];
        [self.overlayWindow makeKeyAndVisible];
        [_hudStack removeObjectAtIndex:0];
        // 更新页面
        if ([hud respondsToSelector:@selector(showImmediately)]) {
            [hud showImmediately];
        }
    } else {
        // 注销页面
        
        [UIApplication.sharedApplication.windows enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(UIWindow *w, NSUInteger idx, BOOL *stop) {
            if ([w isMemberOfClass:UIWindow.class] && w.windowLevel == UIWindowLevelNormal && w.rootViewController && !w.hidden) {
                [w makeKeyWindow];
                *stop = YES;
            }
        }];
        
        [self.overlayWindow setHidden:YES];
        [self.overlayWindow removeFromSuperview];

    }
}

@end
